import pandas as pd
import os
import random
import string
from datetime import datetime

def generate_random_string(length=8):
    """生成随机字符串"""
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def generate_test_cases():
    """生成1000条测试用例"""
    test_cases = []
    case_id = 1
    
    # 1. 登录功能测试用例 (100条)
    for i in range(100):
        if i == 0:
            # 基本登录成功场景
            scenario = "正常登录"
            username = "valid_user"
            password = "ValidPass123"
            expected = "成功登录系统，进入主界面"
            priority = "高"
        elif i == 1:
            # 空用户名
            scenario = "空用户名登录"
            username = ""
            password = "AnyPassword123"
            expected = "提示用户名不能为空"
            priority = "高"
        elif i == 2:
            # 空密码
            scenario = "空密码登录"
            username = "test_user"
            password = ""
            expected = "提示密码不能为空"
            priority = "高"
        elif i == 3:
            # 用户名不存在
            scenario = "用户名不存在登录"
            username = "non_existent_user"
            password = "Password123"
            expected = "提示用户名或密码错误"
            priority = "高"
        elif i == 4:
            # 密码错误
            scenario = "密码错误登录"
            username = "valid_user"
            password = "WrongPassword123"
            expected = "提示用户名或密码错误"
            priority = "高"
        elif i < 20:
            # 各种边界情况
            scenario = f"特殊字符用户名登录_{i}"
            special_chars = ["!@#$%^&*()", "中文用户名", "username.with.dot", "user-name", "user_name"]
            username = special_chars[i % len(special_chars)]
            password = "ValidPass123"
            expected = "正确处理特殊字符，成功登录或给出适当提示"
            priority = "中"
        elif i < 40:
            # 密码强度测试
            scenario = f"密码强度测试_{i}"
            weak_passwords = ["123456", "password", "qwerty", "abc123", "admin123"]
            username = "test_user"
            password = weak_passwords[i % len(weak_passwords)] if i < 35 else generate_random_string(12)
            expected = "弱密码给出强度提示，强密码允许登录"
            priority = "中"
        else:
            # 其他登录相关测试
            scenario = f"登录相关测试_{i}"
            username = generate_random_string(8)
            password = generate_random_string(10)
            expected = "系统正确响应登录请求"
            priority = "低"
        
        test_cases.append({
            '测试用例ID': f'TC{case_id:04d}',
            '测试功能': '用户登录',
            '测试描述': scenario,
            '输入数据': f'用户名: {username}, 密码: {password}',
            '预期结果': expected,
            '实际结果': '',
            '测试状态': '未执行',
            '优先级': priority
        })
        case_id += 1
    
    # 2. 角色管理功能测试用例 (200条)
    role_functions = [
        "角色列表查看", "角色创建", "角色编辑", "角色删除", "角色权限分配",
        "角色搜索", "角色排序", "角色详情查看", "角色状态切换", "角色批量操作"
    ]
    
    for func in role_functions:
        for i in range(20):
            if i == 0:
                # 基本功能测试
                scenario = f"{func}_基本操作"
                input_data = f"执行{func}的标准操作"
                expected = f"成功完成{func}操作"
                priority = "高"
            elif i < 5:
                # 边界情况测试
                scenario = f"{func}_边界情况_{i}"
                input_data = f"特殊条件下执行{func}"
                expected = f"系统正确处理{func}的边界情况"
                priority = "中"
            else:
                # 随机测试场景
                scenario = f"{func}_测试场景_{i}"
                input_data = f"测试数据: {generate_random_string(10)}"
                expected = f"系统正确响应{func}请求"
                priority = "低"
            
            test_cases.append({
                '测试用例ID': f'TC{case_id:04d}',
                '测试功能': '角色管理',
                '测试描述': scenario,
                '输入数据': input_data,
                '预期结果': expected,
                '实际结果': '',
                '测试状态': '未执行',
                '优先级': priority
            })
            case_id += 1
    
    # 3. 对话功能测试用例 (300条)
    dialogue_types = [
        "文本对话", "多轮对话", "上下文理解", "特殊指令处理", "复杂问题解答",
        "长文本回复", "错误修正", "情感分析", "角色一致性", "知识问答"
    ]
    
    for dialogue_type in dialogue_types:
        for i in range(30):
            if i == 0:
                # 基本对话测试
                scenario = f"{dialogue_type}_基本测试"
                input_data = f"输入标准的{dialogue_type}请求"
                expected = f"AI正确响应{dialogue_type}请求"
                priority = "高"
            elif i < 10:
                # 特殊情况测试
                scenario = f"{dialogue_type}_特殊场景_{i}"
                special_inputs = [
                    "你好，能帮我解释一下量子力学吗？",
                    "如何制作一杯完美的咖啡？",
                    "写一首关于春天的诗。",
                    "1 + 1 等于多少？",
                    "用英文介绍一下中国的长城。",
                    "如果我现在在北京，去上海最快的方式是什么？",
                    "如何学习编程？",
                    "解释一下机器学习的基本原理。",
                    "什么是区块链技术？"
                ]
                input_data = special_inputs[i-1]
                expected = f"AI能够理解并回答{dialogue_type}的特殊问题"
                priority = "中"
            else:
                # 随机对话测试
                scenario = f"{dialogue_type}_随机测试_{i}"
                input_data = f"测试问题: {generate_random_string(15)}"
                expected = f"AI能够适当响应{dialogue_type}请求"
                priority = "低"
            
            test_cases.append({
                '测试用例ID': f'TC{case_id:04d}',
                '测试功能': 'AI对话',
                '测试描述': scenario,
                '输入数据': input_data,
                '预期结果': expected,
                '实际结果': '',
                '测试状态': '未执行',
                '优先级': priority
            })
            case_id += 1
    
    # 4. 系统功能测试用例 (200条)
    system_functions = [
        "系统登录", "系统注册", "密码重置", "个人信息管理", "消息通知",
        "数据统计", "日志查看", "系统设置", "帮助文档", "退出登录"
    ]
    
    for func in system_functions:
        for i in range(20):
            if i == 0:
                scenario = f"{func}_标准操作"
                input_data = f"执行{func}的正常操作流程"
                expected = f"成功完成{func}操作"
                priority = "高"
            elif i < 5:
                scenario = f"{func}_异常处理_{i}"
                input_data = f"在{func}过程中模拟异常情况"
                expected = f"系统能够优雅处理{func}中的异常"
                priority = "中"
            else:
                scenario = f"{func}_随机测试_{i}"
                input_data = f"随机输入测试{func}"
                expected = f"系统正确响应{func}请求"
                priority = "低"
            
            test_cases.append({
                '测试用例ID': f'TC{case_id:04d}',
                '测试功能': '系统功能',
                '测试描述': scenario,
                '输入数据': input_data,
                '预期结果': expected,
                '实际结果': '',
                '测试状态': '未执行',
                '优先级': priority
            })
            case_id += 1
    
    # 5. 性能和兼容性测试用例 (200条)
    performance_tests = [
        "响应时间测试", "并发用户测试", "大数据量测试", "长时间运行测试", "资源占用测试",
        "浏览器兼容性", "移动端兼容性", "网络波动适应", "低配置设备适配", "高分辨率适配"
    ]
    
    for test_type in performance_tests:
        for i in range(20):
            if i == 0:
                scenario = f"{test_type}_标准测试"
                input_data = f"按照标准流程执行{test_type}"
                expected = f"系统满足{test_type}的性能要求"
                priority = "中"
            elif i < 5:
                scenario = f"{test_type}_极限测试_{i}"
                input_data = f"在极限条件下测试{test_type}"
                expected = f"系统在极限条件下能够稳定运行或给出合理提示"
                priority = "中"
            else:
                scenario = f"{test_type}_随机测试_{i}"
                input_data = f"随机条件下测试{test_type}"
                expected = f"系统在各种条件下表现稳定"
                priority = "低"
            
            test_cases.append({
                '测试用例ID': f'TC{case_id:04d}',
                '测试功能': '性能兼容性',
                '测试描述': scenario,
                '输入数据': input_data,
                '预期结果': expected,
                '实际结果': '',
                '测试状态': '未执行',
                '优先级': priority
            })
            case_id += 1
    
    # 确保生成至少1000条测试用例
    while len(test_cases) < 1000:
        extra_test = {
            '测试用例ID': f'TC{case_id:04d}',
            '测试功能': random.choice(['扩展测试', '综合测试', '边界测试']),
            '测试描述': f'额外测试场景_{len(test_cases) + 1}',
            '输入数据': f'随机测试数据: {generate_random_string(20)}',
            '预期结果': '系统能够正确响应并处理请求',
            '实际结果': '',
            '测试状态': '未执行',
            '优先级': '低'
        }
        test_cases.append(extra_test)
        case_id += 1
    
    # 创建DataFrame
    df = pd.DataFrame(test_cases)
    
    # 生成Excel文件
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    excel_file = f'AI角色模拟应用测试用例_1000条_{timestamp}.xlsx'
    
    # 分批次写入以避免内存问题
    chunk_size = 500
    with pd.ExcelWriter(excel_file, engine='openpyxl') as writer:
        # 先写入表头
        if len(df) > 0:
            df.iloc[:0].to_excel(writer, index=False, sheet_name='测试用例')
            
            # 分块写入数据
            for i in range(0, len(df), chunk_size):
                chunk = df.iloc[i:i+chunk_size]
                startrow = i + 1  # +1 for header
                chunk.to_excel(writer, index=False, sheet_name='测试用例', startrow=startrow, header=False)
    
    print(f"测试用例已成功生成到文件: {excel_file}")
    print(f"共生成 {len(test_cases)} 条测试用例")

if __name__ == "__main__":
    # 检查pandas和openpyxl是否安装
    try:
        import pandas as pd
        try:
            import openpyxl
        except ImportError:
            print("正在安装openpyxl库...")
            os.system('pip install openpyxl')
        
        generate_test_cases()
    except ImportError:
        print("正在安装pandas库...")
        os.system('pip install pandas openpyxl')
        # 重新导入并执行
        import pandas as pd
        generate_test_cases()